package com.example.com.ddai.others;



import java.security.InvalidKeyException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import android.util.Base64;

public class DES {

	private byte[] desKey;
	private static DES instance = null;
	DESKeySpec dks;
	public static DES getInstance(String desKey) throws InvalidKeyException{
		if(instance == null){
			
			instance = new DES(desKey);
		}
		return instance;
	}

	private DES(String desKey) throws InvalidKeyException {
		this.desKey = desKey.getBytes();
		dks = new DESKeySpec(desKey.getBytes());
	}

	public  byte[] desEncrypt(byte[] plainText) throws Exception {
		SecureRandom sr = new SecureRandom();
	
	
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey key = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.ENCRYPT_MODE, key, sr);
		byte data[] = plainText;
		byte encryptedData[] = cipher.doFinal(data);
		return encryptedData;
	}

	public byte[] desDecrypt(byte[] encryptText) throws Exception {
		SecureRandom sr = new SecureRandom();

		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey key = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.DECRYPT_MODE, key, sr);
		byte encryptedData[] = encryptText;
		byte decryptedData[] = cipher.doFinal(encryptedData);
		return decryptedData;
	}

	public String encrypt(String input) throws Exception {
		String result = base64Encode(desEncrypt(input.getBytes()));
		result = result.trim();
		return result;
	}

	public String decrypt(String input) throws Exception {
		byte[] result = Base64.decode(input, Base64.DEFAULT);
		return new String(desDecrypt(result));
	}

	public static void main(String[] args) throws Exception {
		String key = "androidd";
		String input = "xia_guang_yuan@sina.cn";
		DES crypt = new DES(key);
		System.out.println("Encode:" + crypt.encrypt(input));
		System.out.println("Decode:" + crypt.decrypt(crypt.encrypt(input)));
	}

	public String base64Encode(byte[] s) {
		if (s == null)
			return null;
		return Base64.encodeToString(s, Base64.DEFAULT);

	}
}